package com.yc.Testjvm.cas;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 多线程同步经典例子：银行账户存取
 * 操作：
 * 存10000次，每次+1
 * 取10000次，每次-2
 * 正确预期结果：count=0
 * @author yc
 *
 */
public class CASdemo {
	
	//账户初始金额100
	public static AtomicInteger count = new AtomicInteger(10000);

	public static void main(String[] args) {
		System.out.println("账户初始金额" + count.get() + "，存取完后预期0");
		getThread2 getT = new getThread2();
		setThread2 setT = new setThread2();
		getT.start();
		setT.start();
		try {
			getT.join();
			setT.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("存取完后实际金额为：" + count.get());
		
		
	}

}

class getThread2 extends Thread {

	@Override
	public void run() {
		int lastCount = CASdemo.count.get();
		int num = 0;
		while(num < 10000) {
			
			if (CASdemo.count.compareAndSet(lastCount, lastCount-2)) {
				num++;//成功操作一次
			} else {
				System.out.println("get fauilt");
				lastCount = CASdemo.count.get();
			}
			
		}
	}
	
}

class setThread2 extends Thread {

	@Override
	public void run() {
//		int lastCount = CASdemo.count.get();
		int num = 0;
		while(num < 10000) {
			CASdemo.count.incrementAndGet();
			num++;
//			if (CASdemo.count.compareAndSet(lastCount, lastCount+1)) {
//				num++;//成功操作一次
//			} else {
//				System.out.println("set fauilt");
//				lastCount = CASdemo.count.get();
//			}
			
		}
	}
	
}